import { hashHistory } from 'dva/router';
import { showLoading, hideLoading } from 'react-redux-loading-bar';
import { login, logout, getMenu } from '../services/service';


export default {
  namespace: 'app',
  state: {
    current: 'dashboard',
    collapsed: false,
    account: null,
    islogin: false,
    menuTheme: 'dark',
    menuList: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({ pathname }) => {
        dispatch({
          type: 'getMenu',
          payload: {
          },
        });
      });
    },
  },

  effects: {
    *login({ payload, }, { call, put, select }) { // eslint-disable-line
      try {
        yield put(showLoading());// 开始顶部进度条
        const response = yield call(login, payload);
        if (response.code === 200) {
          yield put({
            type: 'save',
            payload: { account: response.data, islogin: true, current: 'dashboard' },
          });
          const response1 = yield call(getMenu, {});
          if (response1.code === 200) {
            sessionStorage.setItem('loginMenu', JSON.stringify(response1.data));
          }
          sessionStorage.setItem('loginUser', JSON.stringify(response.data));
          hashHistory.push('/dashboard');
        } else {
          yield put({
            type: 'save',
            payload: { account: { username: payload.username }, islogin: false },
          });
        }
      } finally {
        yield put(hideLoading());// 结束顶部进度条
      }
    },
    *logout({ payload }, { call, put, select }) {
      try {
        yield put(showLoading());// 开始顶部进度条
        const account = yield select(state => state.app.account);
        const response = yield call(logout);
        if (response.code === 200) {
          sessionStorage.removeItem('loginUser');
          sessionStorage.removeItem('loginMenu');
          yield put({
            type: 'save',
            payload: { account: { username: account ? account.username : null }, islogin: false },
          });
        }
      } finally {
        yield put(hideLoading());// 结束顶部进度条
      }
    },
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

};
